from datetime import datetime
from typing import Optional
from uuid import UUID, uuid4

from bisheng.database.base import session_getter
from bisheng.database.models.base import SQLModelSerializable
from sqlalchemy import Column, DateTime, String, Text, text, desc
from sqlmodel import Field, SQLModel


class EquipmentInfoBase(SQLModelSerializable):
    id: UUID = Field(nullable=False, primary_key=True, description='唯一ID')
    equipment: str = Field(sa_column=Column(String(length=255), default=''), description='设备名称')
    fault: str = Field(sa_column=Column(String(length=255),default=''), description='故障')
    line: str = Field(sa_column=Column(String(length=255), default=''), description='线路')
    equipment_id: str = Field(sa_column=Column(String(length=255), default=''), description='设备ID')
    equipment_type: str = Field(sa_column=Column(String(length=255), default=''), description='设备类型')
    loop_diagrams: str = Field(sa_column=Column(String(length=255), default=''), description='回路图')
    type: str = Field(sa_column=Column(String(length=255), default=''), description='pic or mp4')
    create_time: Optional[datetime] = Field(
        sa_column=Column(DateTime, nullable=False, server_default=text('CURRENT_TIMESTAMP')))


class EquipmentInfo(EquipmentInfoBase, table=True):
    id: UUID = Field(default_factory=uuid4, primary_key=True, unique=True)


class EquipmentInfoDao:
    @staticmethod
    def create_equipment_info(equipment_info: EquipmentInfo) -> EquipmentInfo:
        """
        创建新的故障工单
        :param fault_work_ticket: FaultWorkTicket 对象
        :return: 创建并保存到数据库的 FaultWorkTicket 对象
        """
        with session_getter() as session:
            # 确保 fault_work_ticket 有一个 UUID
            if not equipment_info.id:
                equipment_info.id = uuid4()
            session.add(equipment_info)
            session.commit()
            session.refresh(equipment_info)
            return equipment_info

    @staticmethod
    def get_equipment_info_by_id(id: str) -> EquipmentInfo:
        with session_getter() as session:
            query = session.query(EquipmentInfo).filter(EquipmentInfo.id == id)
            return query.first()

    @staticmethod
    def get_equipment_info_by_equipment_name(equipment: str, fault: str) -> EquipmentInfo:
        with session_getter() as session:
            query = session.query(EquipmentInfo).filter(EquipmentInfo.equipment == equipment,
                                                        EquipmentInfo.fault == fault)
            return query.all()

    @staticmethod
    def get_all_loop_diagrams():
        with session_getter() as session:
            query = session.query(EquipmentInfo).filter(EquipmentInfo.type == 'pic')
            return query.all()

    @staticmethod
    def get_all_video():
        with session_getter() as session:
            query = session.query(EquipmentInfo).filter(EquipmentInfo.type == 'mp4')
            return query.all()
